package ac.snu.street;

import java.util.Arrays;
import java.util.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class TCPServer implements Runnable {
	Socket client;
	StreetDB database;

	public TCPServer(Socket c, StreetDB db) {
		client = c;
		database = db;
	}

	@Override
	public void run() {
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(
					client.getInputStream()));
			PrintWriter out = new PrintWriter(client.getOutputStream(), true);

			String str = in.readLine();
			System.out.println("S: Received: " + str); // debug
			String[] t = str.split("\t");

			// case Post
			if (str.startsWith("POST")) {
				String contents = t[4];

				str = in.readLine();
				while (str != null) {
					contents += "\n" + str;
					str = in.readLine();
				}
				
				int newId = database.put(t[1], t[2], t[3], contents);
				out.println("DONE\t"+newId);
			// case Request
			} else if (str.startsWith("RQST")) {
				List<String> result;
				if (t[1].equals("ID")) {
					result = database.searchById(Arrays.copyOfRange(t, 2, t.length));
				} else {
					result = database.searchByLocation(t[1], t[2], t[3]);
				}

				for (String note : result) {
					out.println("DATA" + "\t" + note);
				}
				out.println("DATA\tEND");

			// case Update
			} else if (str.startsWith("UPDT")) {
				String contents = t[2];

				str = in.readLine();
				while (str != null) {
					contents += "\n" + str;
					str = in.readLine();
				}
				System.out.println(contents);
				database.update(t[1], contents);
				
			// case delete
			} else if (str.startsWith("DELT")) {
				database.delete(t[1]);
			}
			
			client.shutdownOutput();
		} catch (Exception e) {
			System.out.println("S: Error");
			e.printStackTrace();
		} finally {
			try {
				client.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("S: Done.");
		}
	}
}